package com.weixin.paleituo.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.weixin.paleituo.R;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.AreaInfoBean;
import com.weixin.paleituo.bean.ShippingAddressBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.AreaSelectorDialogFragment;
import com.weixin.paleituo.view.ShopCarToastView;
import com.weixin.paleituo.view.TipsDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * 新建收货地址界面
 * 进行收货地址的添加、编辑
 * 三种类型：
 * 1.{@link NewShippingAddressActivity#TYPE_NEW}从地址管理进入，
 * 普通创建地址，有设为默认tab。
 * 2.{@link NewShippingAddressActivity#TYPE_NEW_USE}从创建订单无地址直接进入，订单地址管理新建地址
 * 直接创建地址并返回数据并使用，有设为默认tab
 * 2.{@link NewShippingAddressActivity#TYPE_UPDATE}从地址管理中心，
 * 编辑地址，返回地址列表，没有设为默认tab
 * 2.{@link NewShippingAddressActivity#TYPE_UPDATE_USE}从创建订单 -> 地址列表 -> 编辑地址，
 * 编辑地址，返回地址列表，非默认有设为默认tab
 *
 * @author fengzhen
 * @version v1.0, 2018/3/27
 */
public class NewShippingAddressActivity extends BaseActivity implements TextWatcher {
    /**
     * 创建新地址
     */
    public static final int TYPE_NEW = 0x0;
    /**
     * 创建新地址,并且使用新地址
     */
    public static final int TYPE_NEW_USE = 0x2;
    /**
     * 修改配送地址
     */
    public static final int TYPE_UPDATE = 0x3;
    /**
     * 修改配送地址,并且使用新地址
     */
    public static final int TYPE_UPDATE_USE = 0x1;

    @BindView(R.id.iv_back_layout_head)
    ImageView mIvBackLayoutHead;
    @BindView(R.id.tv_title_layout_head)
    TextView mTvTitleLayoutHead;
    @BindView(R.id.tv_small_title_layout_head)
    TextView mTvSmallTitleLayoutHead;
    @BindView(R.id.iv_arrow_layout_head)
    ImageView mIvArrowLayoutHead;
    @BindView(R.id.ll_arrowroot_layout_head)
    LinearLayout mLlArrowrootLayoutHead;
    @BindView(R.id.ll_headroots_layout_head)
    LinearLayout mLlHeadrootsLayoutHead;
    @BindView(R.id.edit_user_activity_new_shipping_address)
    EditText mEditUserActivityNewShippingAddress;
    @BindView(R.id.relative_user_activity_new_shipping_address)
    RelativeLayout mRelativeUserActivityNewShippingAddress;
    @BindView(R.id.edit_tel_activity_new_shipping_address)
    EditText mEditTelActivityNewShippingAddress;
    @BindView(R.id.relative_telephone_activity_new_shipping_address)
    RelativeLayout mRelativeTelephoneActivityNewShippingAddress;
    @BindView(R.id.tv_area_activity_new_shipping_address)
    TextView mTvAreaActivityNewShippingAddress;
    @BindView(R.id.ibtn_area_activity_new_shipping_address)
    ImageButton mIbtnAreaActivityNewShippingAddress;
    @BindView(R.id.relative_area_activity_new_shipping_address)
    RelativeLayout mRelativeAreaActivityNewShippingAddress;
    @BindView(R.id.edit_address_activity_new_shipping_address)
    EditText mEditAddressActivityNewShippingAddress;
    @BindView(R.id.relative_address_activity_new_shipping_address)
    RelativeLayout mRelativeAddressActivityNewShippingAddress;
    @BindView(R.id.btn_save_address_activity_new_shipping_address)
    Button mBtnSaveAddressActivityNewShippingAddress;
    @BindView(R.id.relative_default_activity_new_shipping_address)
    RelativeLayout mRelativeDefaultActivityNewShippingAddress;
    @BindView(R.id.switch_default_activity_new_shipping_address)
    Switch mSwitchDefaultAddress;

    private int mType;
    private TipsDialog mNotSaveDialog;
    private ShippingAddressBean mAddress;

    // 页面信息是否发生改变
    private boolean hasChanged = false;
    private AreaSelectorDialogFragment mAreaSelectorDialog;

    private String isDefault;

    private AreaInfoBean mProvince, mCity, mDistrict;
    private ArrayList<AreaInfoBean> mAreaData;

    /**
     * 跳转新增收货人信息
     *
     * @param type {@link NewShippingAddressActivity#TYPE_NEW } 或 {@link NewShippingAddressActivity#TYPE_NEW_USE }
     * @author fengzhen
     * @version v1.0, 2018/3/27
     */
    public static Intent call2NewShippingAddressActivity(Context context, int type) {
        Intent intent = new Intent(context, NewShippingAddressActivity.class);
        intent.putExtra(Contans.INTENT_TYPE, type);
        return intent;
    }

    /**
     * 跳转修改收货人信息
     *
     * @param type {@link NewShippingAddressActivity#TYPE_UPDATE } 或 {@link NewShippingAddressActivity#TYPE_UPDATE_USE }
     * @param add  待修改地址信息
     * @author fengzhen
     * @version v1.0, 2018/3/27
     */
    public static Intent call2NewShippingAddressActivity(Context context, int type, ShippingAddressBean add) {
        Intent intent = new Intent(context, NewShippingAddressActivity.class);
        intent.putExtra(Contans.INTENT_TYPE, type);
        intent.putExtra(Contans.INTENT_DATA, add);
        return intent;
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTitleLayoutHead.setVisibility(View.VISIBLE);
        if (mType == TYPE_UPDATE_USE) {
            mTvTitleLayoutHead.setText("编辑收货人");
            mBtnSaveAddressActivityNewShippingAddress.setText("保存并使用");
            if (mAddress != null) {
                mEditUserActivityNewShippingAddress.setText(mAddress.getContact());
                mEditTelActivityNewShippingAddress.setText(mAddress.getPhone());
                mTvAreaActivityNewShippingAddress.setText(mAddress.getProvinsName() + mAddress.getCityName() + mAddress.getDistrictName());
                mEditAddressActivityNewShippingAddress.setText(mAddress.getAddress());
                mProvince = new AreaInfoBean(mAddress.getProvinsName(), mAddress.getProvinsId());
                mCity = new AreaInfoBean(mAddress.getCityName(), mAddress.getCityId());
                mDistrict = new AreaInfoBean(mAddress.getDistrictName(), mAddress.getDistrictId());
            }
            mRelativeDefaultActivityNewShippingAddress.setVisibility(mAddress.isdefault() ? View.GONE : View.VISIBLE);
            mSwitchDefaultAddress.setChecked(false);
            isDefault = "1";
            mSwitchDefaultAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    isDefault = isChecked ? "2" : "1";
                    hasChanged = true;
                }
            });
        } else if (mType == TYPE_NEW_USE) {
            mTvTitleLayoutHead.setText("新建收货人");
            mBtnSaveAddressActivityNewShippingAddress.setText("保存并使用");
            mRelativeDefaultActivityNewShippingAddress.setVisibility(View.VISIBLE);
            mSwitchDefaultAddress.setChecked(false);
            isDefault = "1";
            mSwitchDefaultAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    isDefault = isChecked ? "2" : "1";
                }
            });
        } else if (mType == TYPE_NEW) {
            mTvTitleLayoutHead.setText("新建收货人");
            mBtnSaveAddressActivityNewShippingAddress.setText("保存");
            mRelativeDefaultActivityNewShippingAddress.setVisibility(View.GONE);
//            mSwitchDefaultAddress.setChecked(true);
//            isDefault = "2";
//            mSwitchDefaultAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                @Override
//                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                    isDefault = isChecked ? "2" : "1";
//                }
//            });
        } else if (mType == TYPE_UPDATE) {
            mTvTitleLayoutHead.setText("编辑收货人");
            mBtnSaveAddressActivityNewShippingAddress.setText("保存");
            if (mAddress != null) {
                mEditUserActivityNewShippingAddress.setText(mAddress.getContact());
                mEditTelActivityNewShippingAddress.setText(mAddress.getPhone());
                mTvAreaActivityNewShippingAddress.setText(mAddress.getProvinsName() + mAddress.getCityName() + mAddress.getDistrictName());
                mEditAddressActivityNewShippingAddress.setText(mAddress.getAddress());
                mProvince = new AreaInfoBean(mAddress.getProvinsName(), mAddress.getProvinsId());
                mCity = new AreaInfoBean(mAddress.getCityName(), mAddress.getCityId());
                mDistrict = new AreaInfoBean(mAddress.getDistrictName(), mAddress.getDistrictId());
                mRelativeDefaultActivityNewShippingAddress.setVisibility(View.GONE);
                isDefault = mAddress.isdefault() ? "2" : "1";
            }
        }

        // 监听是否发生了任何修改
        mEditUserActivityNewShippingAddress.addTextChangedListener(this);
        mEditTelActivityNewShippingAddress.addTextChangedListener(this);
        mTvAreaActivityNewShippingAddress.addTextChangedListener(this);
        mEditAddressActivityNewShippingAddress.addTextChangedListener(this);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_new_shipping_address);
        mType = getIntent().getIntExtra(Contans.INTENT_TYPE, TYPE_NEW);
        if (mType == TYPE_UPDATE_USE || mType == TYPE_UPDATE) {
            mAddress = getIntent().getParcelableExtra(Contans.INTENT_DATA);
        }
    }

    @Override
    public void onBackPressed() {
        if (hasChanged) {
            showTipsDialog();
        } else {
            setResult(RESULT_CANCELED);
            finish();
        }
    }

    @OnClick({R.id.iv_back_layout_head,
            R.id.ibtn_area_activity_new_shipping_address,
            R.id.tv_area_activity_new_shipping_address,
            R.id.ibtn_del_user_activity_new_shipping_address,
            R.id.ibtn_del_phone_activity_new_shipping_address,
            R.id.ibtn_del_address_activity_new_shipping_address,
            R.id.btn_save_address_activity_new_shipping_address})
    public void onClickM(View view) {
        switch (view.getId()) {

            case R.id.ibtn_del_user_activity_new_shipping_address:
                mEditUserActivityNewShippingAddress.setText("");
                break;

            case R.id.ibtn_del_phone_activity_new_shipping_address:
                mEditTelActivityNewShippingAddress.setText("");
                break;

            case R.id.ibtn_del_address_activity_new_shipping_address:
                mEditAddressActivityNewShippingAddress.setText("");
                break;

            case R.id.iv_back_layout_head:
                onBackPressed();
                break;

            /**
             *  地址区域选择
             *
             * @author fengzhen
             * @version v1.0, 2018/3/27
             */
            case R.id.ibtn_area_activity_new_shipping_address:
            case R.id.tv_area_activity_new_shipping_address:
                if (mAreaData == null) {
                    getAreaList();
                } else {
                    showAreaSelectorPop(mAreaData);
                }
                break;

            /**
             *  验证并保存地址信息
             *
             * @author fengzhen
             * @version v1.0, 2018/3/27
             */
            case R.id.btn_save_address_activity_new_shipping_address:
                if (checkInfo()) {
                    if (mType == TYPE_UPDATE || mType == TYPE_UPDATE_USE) {
                        updateAddressInfo();
                    } else {
                        saveAddressInfo();
                    }
                }
                break;
        }
    }

    /**
     * 获取全国行政区信息
     *
     * @author fengzhen
     * @version v1.0, 2018/3/31
     */
    private void getAreaList() {
        showLoadingDialog();
        Observable<StatusCode<List<AreaInfoBean>>> areaListObservable =
                ApiUtils.getApi().getAddressInfo(BaseApplication.getToken(), BaseApplication.getUserId());
        HttpUtil.getInstance().toSubscribe(areaListObservable,
                new ProgressSubscriber<List<AreaInfoBean>>(this) {
                    @Override
                    protected void _onNext(StatusCode<List<AreaInfoBean>> statusCode) {
                        dismissLoadingDialog();
                        mAreaData = (ArrayList<AreaInfoBean>) statusCode.getData();
                        showAreaSelectorPop(mAreaData);
                    }

                    @Override
                    protected void _onError(String message) {
                        dismissLoadingDialog();
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 展示所在区域选择Popwindow
     *
     * @author fengzhen
     * @version v1.0, 2018/3/29
     */
    private void showAreaSelectorPop(ArrayList<AreaInfoBean> area) {
        mAreaSelectorDialog = AreaSelectorDialogFragment.newInstance(area, mProvince, mCity, mDistrict);
        mAreaSelectorDialog.showAllowingStateLoss(getSupportFragmentManager(), "area");
    }

    /**
     * DialogFragment调用方法，用于回传选择区域结果
     *
     * @author fengzhen
     * @version v1.0, 2018/3/30
     */
    public void setArea(AreaInfoBean provice, AreaInfoBean city, AreaInfoBean district) {
        if (provice == null || city == null || district == null) return;
        mTvAreaActivityNewShippingAddress.setText(provice.getName() + city.getName() + district.getName());
        mProvince = provice;
        mCity = city;
        mDistrict = district;
    }

    /**
     * 验证地址信息是否完整
     *
     * @return true:通过验证 false:未通过验证
     * @author fengzhen
     * @version v1.0, 2018/3/27
     */
    private boolean checkInfo() {
        if (StringUtils.isEmpty(mEditUserActivityNewShippingAddress.getText().toString())) {
            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
            shopCarToastView.setIcon(R.mipmap.address_error);
            shopCarToastView.setText("请输入联系人姓名");
            shopCarToastView.setDuration(Toast.LENGTH_LONG);
            shopCarToastView.show();
            return false;
        }
        if (!UIUtils.isNick(mEditUserActivityNewShippingAddress.getText().toString())) {
            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
            shopCarToastView.setIcon(R.mipmap.address_error);
            shopCarToastView.setText("联系人姓名只能输入汉字、字母或数字");
            shopCarToastView.setDuration(Toast.LENGTH_LONG);
            shopCarToastView.show();
            return false;
        }
        String tel = mEditTelActivityNewShippingAddress.getText().toString();
        if (StringUtils.isEmpty(tel)) {
            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
            shopCarToastView.setIcon(R.mipmap.address_error);
            shopCarToastView.setText("请输入手机号码");
            shopCarToastView.setDuration(Toast.LENGTH_LONG);
            shopCarToastView.show();
            return false;
        }
        if (!UIUtils.isPhoneNumber(tel)) {
            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
            shopCarToastView.setIcon(R.mipmap.address_error);
            shopCarToastView.setText("手机号码格式不对");
            shopCarToastView.setDuration(Toast.LENGTH_LONG);
            shopCarToastView.show();
            return false;
        }
        if (mProvince == null || mCity == null || mDistrict == null) {
            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
            shopCarToastView.setIcon(R.mipmap.address_error);
            shopCarToastView.setText("请选择所在地区");
            shopCarToastView.setDuration(Toast.LENGTH_LONG);
            shopCarToastView.show();
            return false;
        }
        if (StringUtils.isEmpty(mEditAddressActivityNewShippingAddress.getText().toString())) {
            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
            shopCarToastView.setIcon(R.mipmap.address_error);
            shopCarToastView.setText("请输入详细地址");
            shopCarToastView.setDuration(Toast.LENGTH_LONG);
            shopCarToastView.show();
            return false;
        }
        if (!UIUtils.isNick(mEditAddressActivityNewShippingAddress.getText().toString())) {
            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
            shopCarToastView.setIcon(R.mipmap.address_error);
            shopCarToastView.setText("详细地址只能输入汉字、字母或数字");
            shopCarToastView.setDuration(Toast.LENGTH_LONG);
            shopCarToastView.show();
            return false;
        }
        return true;
    }

    /**
     * 保存地址信息
     *
     * @author fengzhen
     * @version v1.0, 2018/3/27
     */
    private void saveAddressInfo() {
        String userName = mEditUserActivityNewShippingAddress.getText().toString();
        String tel = mEditTelActivityNewShippingAddress.getText().toString();
//        String area = mTvAreaActivityNewShippingAddress.getText().toString();
        final String address = mEditAddressActivityNewShippingAddress.getText().toString();

        Observable<StatusCode<ShippingAddressBean>> addAddressObservable = ApiUtils.getApi().addShippingAddress(
                BaseApplication.getToken(),
                BaseApplication.getUserId(),
                userName,
                tel,
                address,
                mProvince.getId(),
                mCity.getId(),
                mDistrict.getId(),
                isDefault);
        HttpUtil.getInstance().toSubscribe(addAddressObservable,
                new ProgressSubscriber(this) {
                    @Override
                    protected void _onNext(StatusCode statusCode) {
//                        if (mType == TYPE_NEW) {
                        ShopCarToastView shopCarToastView = new ShopCarToastView(NewShippingAddressActivity.this);
                        shopCarToastView.setIcon(R.mipmap.address_success);
                        shopCarToastView.setText("地址新建成功");
                        shopCarToastView.setDuration(Toast.LENGTH_LONG);
                        shopCarToastView.show();
//                        }

                        Intent data = new Intent();
                        ShippingAddressBean addressData = (ShippingAddressBean) statusCode.getData();
                        addressData.setDetailAddress(mProvince.getName() + mCity.getName() + mDistrict.getName() + " " + address);
                        data.putExtra(Contans.INTENT_DATA, addressData);
                        setResult(RESULT_OK, data);
                        finish();
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 修改地址信息
     *
     * @author fengzhen
     * @version v1.0, 2018/3/27
     */
    private void updateAddressInfo() {
        String userName = mEditUserActivityNewShippingAddress.getText().toString();
        String tel = mEditTelActivityNewShippingAddress.getText().toString();
//        String area = mTvAreaActivityNewShippingAddress.getText().toString();
        String address = mEditAddressActivityNewShippingAddress.getText().toString();

        Observable<StatusCode<ShippingAddressBean>> addAddressObservable = ApiUtils.getApi().updateShippingAddress(
                BaseApplication.getToken(),
                BaseApplication.getUserId(),
                mAddress.getId(),
                userName,
                tel,
                address,
                mProvince.getId(),
                mCity.getId(),
                mDistrict.getId(),
                isDefault);
        HttpUtil.getInstance().toSubscribe(addAddressObservable,
                new ProgressSubscriber<ShippingAddressBean>(this) {
                    @Override
                    protected void _onNext(StatusCode<ShippingAddressBean> statusCode) {
//                        if (mType == TYPE_UPDATE) {
                        ShopCarToastView shopCarToastView = new ShopCarToastView(NewShippingAddressActivity.this);
                        shopCarToastView.setIcon(R.mipmap.address_success);
                        shopCarToastView.setText("保存地址成功");
                        shopCarToastView.setDuration(Toast.LENGTH_LONG);
                        shopCarToastView.show();
//                        }
                        Intent data = new Intent();
                        ShippingAddressBean addressData = statusCode.getData();
//                        addressData.setDetailAddress(mProvince.getName() + mCity.getName() + mDistrict.getName() + " " + address);
                        data.putExtra(Contans.INTENT_DATA, addressData);
                        setResult(RESULT_OK, data);
                        finish();
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 未保存信息提示
     *
     * @author fengzhen
     * @version v1.0, 2018/3/28
     */
    private void showTipsDialog() {
        if (mNotSaveDialog == null) {
            mNotSaveDialog = new TipsDialog.Builder(this)
                    .setCancelClickListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mNotSaveDialog.dismiss();
                        }
                    })
                    .setContentView("修改的内容还未保存，确认现在返回吗？")
                    .setLeftButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mNotSaveDialog.dismiss();
                        }
                    })
                    .setRightButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mNotSaveDialog.dismiss();
                            setResult(RESULT_CANCELED);
                            finish();
                        }
                    })
                    .build();
        }
        mNotSaveDialog.show();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        hasChanged = true;
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
}
